<template>
  <view class="trust-fragment-share">
    <!-- 信任碎片生成 -->
    <view class="fragment-generator" v-if="!fragmentGenerated">
      <view class="generator-header">
        <text class="generator-title">生成信任碎片</text>
        <text class="generator-desc">将你的信任关系分享给好友</text>
      </view>
      
      <view class="fragment-form">
        <view class="form-group">
          <text class="form-label">选择卡牌</text>
          <picker 
            :value="selectedCardIndex" 
            :range="cardOptions" 
            range-key="name"
            @change="onCardChange"
          >
            <view class="picker-display">
              <text class="picker-text">{{ selectedCard.name }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
        
        <view class="form-group">
          <text class="form-label">信任值</text>
          <view class="trust-value-display">
            <text class="trust-number">{{ selectedCard.trustValue }}</text>
            <text class="trust-label">/ 100</text>
          </view>
        </view>
        
        <view class="form-group">
          <text class="form-label">分享消息</text>
          <textarea 
            class="message-input"
            v-model="shareMessage"
            placeholder="输入分享消息..."
            maxlength="100"
          />
          <text class="char-count">{{ shareMessage.length }}/100</text>
        </view>
        
        <button class="generate-btn" @click="generateFragment">
          <text class="btn-icon">✨</text>
          <text class="btn-text">生成信任碎片</text>
        </button>
      </view>
    </view>
    
    <!-- 信任碎片展示 -->
    <view class="fragment-display" v-if="fragmentGenerated">
      <view class="fragment-header">
        <text class="fragment-title">信任碎片已生成</text>
        <button class="regenerate-btn" @click="regenerateFragment">
          <text class="btn-text">重新生成</text>
        </button>
      </view>
      
      <view class="fragment-content">
        <!-- 卡牌预览 -->
        <view class="card-preview">
          <view class="preview-card" :class="`trust-${getTrustLevel(selectedCard.trustValue)}`">
            <text class="card-icon">{{ selectedCard.icon }}</text>
            <text class="card-name">{{ selectedCard.name }}</text>
            <view class="trust-progress">
              <view class="progress-bar">
                <view 
                  class="progress-fill" 
                  :style="{ width: selectedCard.trustValue + '%' }"
                ></view>
              </view>
              <text class="trust-text">{{ selectedCard.trustValue }}%</text>
            </view>
          </view>
        </view>
        
        <!-- 分享消息 -->
        <view class="share-message">
          <text class="message-text">{{ shareMessage }}</text>
        </view>
        
        <!-- 二维码 -->
        <view class="qr-code-section">
          <text class="qr-title">扫描二维码接收信任碎片</text>
          <view class="qr-container">
            <canvas 
              id="trustFragmentQR" 
              class="qr-canvas"
              :style="{ width: '200rpx', height: '200rpx' }"
            ></canvas>
          </view>
        </view>
        
        <!-- 分享链接 -->
        <view class="share-link-section">
          <text class="link-title">分享链接</text>
          <view class="link-container">
            <input 
              class="link-input" 
              :value="shareLink" 
              readonly
            />
            <button class="copy-btn" @click="copyLink">
              <text class="btn-text">复制</text>
            </button>
          </view>
        </view>
        
        <!-- 分享按钮 -->
        <view class="share-buttons">
          <button class="share-btn wechat" @click="shareToWechat">
            <text class="btn-icon">💬</text>
            <text class="btn-text">微信</text>
          </button>
          
          <button class="share-btn qq" @click="shareToQQ">
            <text class="btn-icon">🐧</text>
            <text class="btn-text">QQ</text>
          </button>
          
          <button class="share-btn weibo" @click="shareToWeibo">
            <text class="btn-icon">📱</text>
            <text class="btn-text">微博</text>
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import trustCardManager from '@/utils/trust-card-manager.js'

export default {
  name: 'TrustFragmentShare',
  props: {
    cardData: {
      type: Object,
      default: null
    }
  },
  
  data() {
    return {
      selectedCardIndex: 0,
      selectedCard: null,
      shareMessage: '',
      fragmentGenerated: false,
      shareLink: '',
      fragmentId: ''
    }
  },
  
  computed: {
    cardOptions() {
      return trustCardManager.getAllCards().map(card => ({
        ...card,
        name: `${card.name} (${card.currentTrustValue}%)`
      }))
    }
  },
  
  onLoad() {
    this.initData()
  },
  
  methods: {
    // 初始化数据
    initData() {
      if (this.cardData) {
        this.selectedCard = this.cardData
        this.selectedCardIndex = this.cardOptions.findIndex(card => card.id === this.cardData.id)
      } else {
        this.selectedCard = this.cardOptions[0]
      }
      
      this.shareMessage = `我有一张${this.selectedCard.name}，信任值${this.selectedCard.currentTrustValue}%，想要分享给你！`
    },
    
    // 选择卡牌变化
    onCardChange(e) {
      this.selectedCardIndex = e.detail.value
      this.selectedCard = this.cardOptions[this.selectedCardIndex]
      this.shareMessage = `我有一张${this.selectedCard.name}，信任值${this.selectedCard.currentTrustValue}%，想要分享给你！`
    },
    
    // 生成信任碎片
    generateFragment() {
      if (!this.selectedCard) {
        uni.showToast({
          title: '请选择要分享的卡牌',
          icon: 'none'
        })
        return
      }
      
      // 生成碎片ID
      this.fragmentId = this.generateFragmentId()
      
      // 生成分享链接
      this.shareLink = this.generateShareLink()
      
      // 生成二维码
      this.generateQRCode()
      
      this.fragmentGenerated = true
      
      uni.showToast({
        title: '信任碎片生成成功',
        icon: 'success'
      })
    },
    
    // 重新生成碎片
    regenerateFragment() {
      this.fragmentGenerated = false
      this.fragmentId = ''
      this.shareLink = ''
    },
    
    // 生成碎片ID
    generateFragmentId() {
      const timestamp = Date.now()
      const random = Math.random().toString(36).substr(2, 9)
      return `trust_${timestamp}_${random}`
    },
    
    // 生成分享链接
    generateShareLink() {
      const baseUrl = 'https://moe-web.com/trust-fragment'
      // 手动构建查询字符串（兼容uni-app环境）
      const params = {
        id: this.fragmentId,
        cardId: this.selectedCard.id,
        trustValue: this.selectedCard.currentTrustValue,
        message: encodeURIComponent(this.shareMessage)
      }
      const queryString = Object.keys(params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&')
      
      return `${baseUrl}?${queryString}`
    },
    
    // 生成二维码
    generateQRCode() {
      // 这里需要引入二维码生成库，如qrcode.js
      // 暂时使用模拟二维码
      const canvas = document.getElementById('trustFragmentQR')
      if (canvas) {
        const ctx = canvas.getContext('2d')
        ctx.fillStyle = '#000'
        ctx.fillRect(0, 0, 200, 200)
        ctx.fillStyle = '#fff'
        ctx.font = '16px Arial'
        ctx.fillText('QR Code', 50, 100)
      }
    },
    
    // 复制链接
    copyLink() {
      uni.setClipboardData({
        data: this.shareLink,
        success: () => {
          uni.showToast({
            title: '链接已复制',
            icon: 'success'
          })
        }
      })
    },
    
    // 分享到微信
    shareToWechat() {
      this.performShare('wechat')
    },
    
    // 分享到QQ
    shareToQQ() {
      this.performShare('qq')
    },
    
    // 分享到微博
    shareToWeibo() {
      this.performShare('weibo')
    },
    
    // 执行分享
    performShare(platform) {
      const shareData = {
        title: `信任碎片 - ${this.selectedCard.name}`,
        content: this.shareMessage,
        url: this.shareLink,
        imageUrl: this.getCardImageUrl()
      }
      
      // 这里需要调用相应的分享API
      uni.showToast({
        title: `分享到${platform}成功`,
        icon: 'success'
      })
      
      // 记录分享行为
      this.recordShareAction(platform)
    },
    
    // 获取卡牌图片URL
    getCardImageUrl() {
      // 这里应该生成卡牌的图片URL
      return '/static/trust-card-preview.png'
    },
    
    // 记录分享行为
    recordShareAction(platform) {
      // 记录分享行为到信任历史
      trustCardManager.updateCardTrust(
        this.selectedCard.id, 
        5, 
        `分享到${platform}`
      )
    },
    
    // 获取信任等级
    getTrustLevel(trustValue) {
      if (trustValue >= 80) return 'high'
      if (trustValue >= 50) return 'medium'
      if (trustValue >= 20) return 'low'
      return 'broken'
    }
  }
}
</script>

<style scoped>
.trust-fragment-share {
  padding: 20rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

/* 碎片生成器 */
.fragment-generator {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
}

.generator-header {
  text-align: center;
  margin-bottom: 30rpx;
}

.generator-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.generator-desc {
  font-size: 24rpx;
  color: #666;
}

/* 表单样式 */
.fragment-form {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.form-label {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
}

.picker-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12rpx 16rpx;
  background: #f8f9fa;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  cursor: pointer;
}

.picker-text {
  font-size: 22rpx;
  color: #333;
}

.picker-arrow {
  font-size: 20rpx;
  color: #666;
}

.trust-value-display {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 16rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
}

.trust-number {
  font-size: 28rpx;
  font-weight: bold;
  color: #667eea;
}

.trust-label {
  font-size: 20rpx;
  color: #666;
}

.message-input {
  width: 100%;
  min-height: 80rpx;
  padding: 12rpx 16rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 22rpx;
  background: #f8f9fa;
  resize: none;
}

.char-count {
  font-size: 18rpx;
  color: #999;
  text-align: right;
}

.generate-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 16rpx 24rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12rpx;
  font-size: 24rpx;
  font-weight: bold;
  cursor: pointer;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.generate-btn:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 16rpx rgba(102, 126, 234, 0.4);
}

.btn-icon {
  font-size: 20rpx;
}

.btn-text {
  font-size: 22rpx;
}

/* 碎片展示 */
.fragment-display {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.1);
}

.fragment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.fragment-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.regenerate-btn {
  background: #f0f0f0;
  color: #666;
  border: none;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 20rpx;
  cursor: pointer;
}

.fragment-content {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

/* 卡牌预览 */
.card-preview {
  display: flex;
  justify-content: center;
}

.preview-card {
  background: white;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  text-align: center;
  min-width: 200rpx;
}

.preview-card.trust-high {
  border: 3rpx solid #4caf50;
}

.preview-card.trust-medium {
  border: 3rpx solid #ff9800;
}

.preview-card.trust-low {
  border: 3rpx solid #ff5722;
}

.preview-card.trust-broken {
  border: 3rpx solid #f44336;
}

.card-icon {
  font-size: 40rpx;
  display: block;
  margin-bottom: 8rpx;
}

.card-name {
  font-size: 22rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.trust-progress {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.progress-bar {
  width: 100%;
  height: 8rpx;
  background: #e0e0e0;
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 4rpx;
  transition: width 0.5s ease;
}

.trust-high .progress-fill {
  background: #4caf50;
}

.trust-medium .progress-fill {
  background: #ff9800;
}

.trust-low .progress-fill {
  background: #ff5722;
}

.trust-broken .progress-fill {
  background: #f44336;
}

.trust-text {
  font-size: 18rpx;
  color: #666;
  text-align: center;
}

/* 分享消息 */
.share-message {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 16rpx;
}

.message-text {
  font-size: 22rpx;
  color: #333;
  line-height: 1.4;
}

/* 二维码区域 */
.qr-code-section {
  text-align: center;
}

.qr-title {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 16rpx;
}

.qr-container {
  display: flex;
  justify-content: center;
  padding: 20rpx;
  background: white;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.qr-canvas {
  border-radius: 8rpx;
}

/* 分享链接 */
.share-link-section {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.link-title {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
}

.link-container {
  display: flex;
  gap: 8rpx;
}

.link-input {
  flex: 1;
  padding: 12rpx 16rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 20rpx;
  background: #f8f9fa;
}

.copy-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 12rpx 20rpx;
  border-radius: 8rpx;
  font-size: 20rpx;
  cursor: pointer;
}

/* 分享按钮 */
.share-buttons {
  display: flex;
  gap: 12rpx;
  justify-content: center;
}

.share-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 12rpx 20rpx;
  border: none;
  border-radius: 8rpx;
  font-size: 20rpx;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.share-btn.wechat {
  background: #07c160;
  color: white;
}

.share-btn.qq {
  background: #12b7f5;
  color: white;
}

.share-btn.weibo {
  background: #e6162d;
  color: white;
}

.share-btn:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
}

/* 响应式设计 */
@media (max-width: 768rpx) {
  .trust-fragment-share {
    padding: 16rpx;
  }
  
  .fragment-generator,
  .fragment-display {
    padding: 24rpx;
  }
  
  .share-buttons {
    flex-direction: column;
  }
  
  .share-btn {
    justify-content: center;
  }
}
</style>

